"""
数据库操作
"""
import json

import pymysql

from zonghe.caw import file_reader


def connect(db_info):  #connect:连接
    """
    建立数据库链接
    :param db_info: 数据库信息
    :return: 数据库链接
    """
    try:
        r=pymysql.connect(
            user=db_info["user"],
            password=db_info["pwd"],
            host=db_info["host"],
            port=db_info["port"],
            database=db_info["name"],
            charset='utf8'  #charset：编码
        )
        print("连接数据库成功")
        return r
    except Exception as e:
        print("链接数据库异常",e)

def execute(connect,sql):   #execute:执行
    """
    执行sql语句
    :param conn:数据库连接
    :param sql: sql语句
    :return:
    """
    try:
        cursor=connect.cursor() #链接上获取游标
        cursor.execute(sql) #在游标上执行sql
        connect.commit()  #在链接上提交
        r=cursor.fetchall() #获取全部数据
        print("执行SQL语句",sql,"成功")
        return r
    except Exception as e:
        print("执行SQL语句",sql,"失败，异常信息为",e)

def dis_connect(connect):
    """
    断开链接
    :param conn:要断开的链接
    :return:
    """
    try:
        connect.close()
        print("断开数据库链接成功")
    except Exception as e:
        print("断开数据库链接异常",e)


if __name__ == '__main__':
    #测试链接数据库
    db_info=json.loads(file_reader.read_config("db_info"))
    r=connect(db_info)
    #测试执行sql语句
    ret=execute(r,"select * from member where Mobilephone like '1886666888%'")
    ret=execute(r,"delete from member where Mobilephone like '1886666888%'")
    print(ret)
    #断开链接
    dis_connect(r)

